package util;

import userModule.daoImpl.Library_UserDaoImpl;
import vo.Library_User;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;
import java.util.Scanner;

public class Tools {

    static Library_UserDaoImpl userDao = new Library_UserDaoImpl();

    static Scanner scanner = new Scanner(System.in);

    static Random rand = new Random();

    /**
     * 因为很多地方都需要使用登录功能，所以可以做封装
     * @return
     * @throws UnsupportedEncodingException
     */
    public static Library_User login() throws UnsupportedEncodingException {

        System.out.println("=====登录=====");
        System.out.println("用户名:");
        String username = scanner.nextLine();
        System.out.println("密码:");
        String password = MD5Encryption.getEncryption(scanner.nextLine());

        Library_User user = userDao.selectUserByUsernameAndPassword(username, password);

        return user;
    }

    /**
     * 封装一个写日志的方法
     * @param operate
     * @param result
     * @throws IOException
     */
    public static void writeLog(String operate,String result) throws IOException {

        BufferedWriter bf = new BufferedWriter(new FileWriter(Constant.LOGPATH,true));
        //获取当前时间
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        //模拟操作节点ip
        String ip = rand.nextInt(256)+"."+rand.nextInt(256)+"."+rand.nextInt(256)+"."+rand.nextInt(256);

        bf.write(date+"\t"+ip+"\t"+operate+"\t"+result);

        bf.flush();

        bf.close();
    }
}
